import { Injectable } from '@nestjs/common';
import { ObjectId } from 'mongodb';
import { profileModel } from 'src/user/entity/profile.entity';
import { Award, awardModel } from './entities/award.entity';

@Injectable()
export class AwardService {
  /**
   *
   * @param openid
   * @returns {string} 该奖励的唯一id
   */
  public async finishedAward(
    openid: string,
    name: string,
    tags: Array<string>,
  ): Promise<string> {
    const MAXNUM = 10;
    const objectid = new ObjectId();
    const tomato = Math.ceil(MAXNUM * Math.random());
    profileModel.initializeOrderedBulkOp((v) => {
      v.find({ openid, 'property.tomato': { $exists: true } })
        .upsert()
        .updateOne([
          {
            $set: { 'property.tomato': { $sum: ['$property.tomato', tomato] } },
          },
        ]);
    });
    await this.createAwardOrItem(
      openid,
      objectid.toHexString(),
      tomato,
      name,
      tags,
    );
    return objectid.toHexString();
  }

  async createAwardOrItem(
    openid: string,
    id: string,
    tomato: number,
    name: string,
    tags: string[],
  ) {
    const awards = await awardModel.findOne({ openid });
    if (awards) {
      await awardModel.updateOne(
        { openid },
        { $push: { awards: { id, tomato, name, tags } } },
      );
    } else {
      await awardModel.insertOne({
        openid,
        awards: [{ id, tomato, name, tags }],
      });
    }
  }

  async findItemById(openid: string, awardId: string) {
    const award = await awardModel.findOne<Award>({ openid });
    if (award) {
      for (const a of award.awards) {
        if (a.id === awardId) {
          return a;
        }
      }
    }
    return null;
  }
}
